import React, { ReactNode, useState } from "react"
import * as auth from'utils/auth-provider'
import { http } from "utils/http"
import { useMount } from "utils"
import { useAsync } from "utils/useAsync"
import { FullPageErrorFallback, FullpageLoading } from "components/lib"
import { useQueryClient } from "react-query"
import { User } from "types"

interface AuthFrom{
  username:string,
  password:string
}

const bootstrapUser = async () =>{
  let user = null
  const token  = auth.getToken()
  if(token){
    const data = await http("me",{token})
    user = data.user
  }
  return user
}


const AuthContext =  React.createContext<
{
  user:User |null,
  register:(form:AuthFrom)=>Promise<void>
  login:(form:AuthFrom)=>Promise<void>
  logout:()=>Promise<void>
}|undefined
>(undefined)
AuthContext.displayName= 'AuthContext'


export default function AuthProvider ({children}:{children:ReactNode}){
  // const [user,setUser] = useState<User |null >(null)

  const {
    data:user,
    error,
    isLoading,
    isIdle,
    isError,
    run,
    setData:setUser
  } = useAsync<User |null> ()

  // const queryClient = useQueryClient();
  // const login = (form:AuthFrom) => auth.login(form).then(user => setUser(user))
  // const register = (form:AuthFrom) => auth.register(form).then(user => setUser(user))
  const login = (form:AuthFrom) => auth.login(form).then(setUser)
  const register = (form:AuthFrom) => auth.register(form).then(setUser)
  const logout = () => auth.logout().then( () =>{
    setUser(null);
  })

  useMount(()=>{
    run(bootstrapUser())
  })
  
  if(isIdle||isLoading){
    return <FullpageLoading></FullpageLoading>
  }

  if(isError){
    return <FullPageErrorFallback error={error}></FullPageErrorFallback>
  }

  return <AuthContext.Provider children={children} value={{user,login,register,logout}}></AuthContext.Provider>
}

export const useAuth =()=>{
  const context = React.useContext(AuthContext)
  if(!context){
    throw new Error("useAuth 必须在AuthProvider中使用")
  }
  return context
}

